'use strict'
/*
//引入模块
let 
    http = require('http');

//创建http服务器
let server = http.createServer(function(req,res){
    res.writeHead(200);
    res.write('<head><meta charset="UTF-8"/></head>');
    res.end('打印出来了')
})

//监听端口
let port=(8080);
server.listen(port);

//打印服务器运行地址
console.log(`server is runing at http://127.0.0.1:${port}`);
*/

/*
//引用模块
let 
    http = require('http'),
    fs = require('fs');

//创建http服务器
let server = http.createServer((req,res)=>{
    let path='./index.html';
    fs.readFile(path,(err,data)=>{
        if(err){
            res.write(err);
        }
        else{
            res.write('<head><meta charset="UTF-8"/></head>');
            res.end(data);
        }
    })
})

//定义、监听端口
let port = 8540;
server.listen(port);

//打印服务器运行地址
console.log(`server is runing at http://127.0.0.1:${port}`);
*/

//引用模块
let
     http = require('http'),
     fs = require('fs'),
     path = require('path');

//解析路径默认当前路径
let rootPath = path.resolve(process.argv[2] || '.');


//创建服务器
let server=http.createServer((req,res)=>{
    //打印头文件
    res.writeHead(200);
    res.write('<head><meta charset="UTF-8"/></head>');
    //获取请求路径
    let qqPath= req.url;
    //判断请求路径是否浏览器图标
    if(qqPath !== './favicon.ico'){
        //拼接绝对路径，当前路径+请求路径
        let fullPath=path.join(rootPath,qqPath);
        //获取当前文件的根目录
        let file = fs.readdirSync(fullPath);
        file.forEach(x=>{
            if(x === 'index.html' || x === 'out.html'){
                let filePath = path.join(fullPath,x);
                fs.readFile(filePath,(err,data)=>{
                    if(!err){
                        res.write('<head><meta charset="UTF-8"/></head>')
                        res.write(data);
                    }
                    else{
                        res.end(err);
                    }
                })
            }
        })
    }
})

//监听端口
let port = 4800;
server.listen(port);

//打印服务器运行地址
console.log(`server is runing at http://127.0.0.1:${port}`);